"""
用户服务配置
============

继承RedFire框架配置，添加用户服务特有配置。
"""

from pathlib import Path
from pydantic import Field
from typing import Dict, Any
from redfire_framework import RedFireSettings


class UserServiceSettings(RedFireSettings):
    """
    用户服务配置
    
    继承RedFire框架基础配置，添加用户服务特有配置项。
    使用新的命名数据库配置架构，支持多数据库连接。
    """
    
    # 覆盖父类的服务名称，提供更具体的默认值
    service_name: str = Field(default="user_service", env="REDFIRE_SERVICE_NAME", description="用户服务名称")
    
    # 覆盖父类的API端口配置
    api_port: int = Field(default=8002, env="REDFIRE_USER_SERVICE_PORT", description="用户服务API端口")
    
    # 命名数据库配置
    user_primary_url: str = Field(
        default="mysql+aiomysql://redfire_app:redfire_app_2025@localhost:3307/redfire_trading", 
        env="USER_SERVICE_PRIMARY_DATABASE_URL",
        description="用户服务主数据库连接URL"
    )
    user_primary_pool_size: int = Field(
        default=5, 
        env="USER_SERVICE_PRIMARY_POOL_SIZE",
        description="主数据库连接池大小"
    )
    
    # 可选的只读副本配置
    user_readonly_url: str = Field(
        default="mysql+aiomysql://redfire_app:redfire_app_2025@localhost:3307/redfire_trading", 
        env="USER_SERVICE_READONLY_DATABASE_URL",
        description="用户服务只读数据库连接URL（可选）"
    )
    user_readonly_pool_size: int = Field(
        default=20, 
        env="USER_SERVICE_READONLY_POOL_SIZE",
        description="只读数据库连接池大小"
    )
    
    # 可选的会话缓存配置
    session_cache_url: str = Field(
        default="redis://:redfire_redis_2025@localhost:6379/0", 
        env="USER_SERVICE_SESSION_CACHE_URL",
        description="会话缓存数据库连接URL（可选，Redis）"
    )
    session_cache_pool_size: int = Field(
        default=10, 
        env="USER_SERVICE_SESSION_CACHE_POOL_SIZE",
        description="会话缓存连接池大小"
    )
    
    # 通用数据库配置
    database_pool_timeout: int = Field(
        default=30, 
        env="USER_SERVICE_DATABASE_POOL_TIMEOUT",
        description="数据库连接超时"
    )
    database_echo: bool = Field(
        default=False, 
        env="USER_SERVICE_DATABASE_ECHO",
        description="是否输出SQL日志"
    )
    
    # 用户服务特有配置
    password_min_length: int = Field(default=8, env="USER_SERVICE_PASSWORD_MIN_LENGTH", description="密码最小长度")
    password_require_uppercase: bool = Field(default=True, env="USER_SERVICE_PASSWORD_REQUIRE_UPPERCASE", description="密码是否需要大写字母")
    password_require_numbers: bool = Field(default=True, env="USER_SERVICE_PASSWORD_REQUIRE_NUMBERS", description="密码是否需要数字")
    password_require_special: bool = Field(default=True, env="USER_SERVICE_PASSWORD_REQUIRE_SPECIAL", description="密码是否需要特殊字符")
    
    # 会话配置
    session_timeout: int = Field(default=3600, env="USER_SERVICE_SESSION_TIMEOUT", description="会话超时时间(秒)")
    max_login_attempts: int = Field(default=5, env="USER_SERVICE_MAX_LOGIN_ATTEMPTS", description="最大登录尝试次数")
    lockout_duration: int = Field(default=900, env="USER_SERVICE_LOCKOUT_DURATION", description="账户锁定时长(秒)")
    
    # 用户注册配置
    require_email_verification: bool = Field(default=True, env="USER_SERVICE_REQUIRE_EMAIL_VERIFICATION", description="是否需要邮箱验证")
    allow_duplicate_email: bool = Field(default=False, env="USER_SERVICE_ALLOW_DUPLICATE_EMAIL", description="是否允许重复邮箱")
    default_user_role: str = Field(default="user", env="USER_SERVICE_DEFAULT_USER_ROLE", description="默认用户角色")
    
    # 审计配置
    enable_audit_log: bool = Field(default=True, env="USER_SERVICE_ENABLE_AUDIT_LOG", description="是否启用审计日志")
    audit_retention_days: int = Field(default=90, env="USER_SERVICE_AUDIT_RETENTION_DAYS", description="审计日志保留天数")
    
    # 通知配置
    enable_notifications: bool = Field(default=True, env="USER_SERVICE_ENABLE_NOTIFICATIONS", description="是否启用通知")
    notification_email_from: str = Field(default="noreply@redfire.com", env="USER_SERVICE_NOTIFICATION_EMAIL_FROM", description="通知邮件发送地址")
    
    @property
    def password_policy(self) -> dict:
        """获取密码策略配置"""
        return {
            "min_length": self.password_min_length,
            "require_uppercase": self.password_require_uppercase,
            "require_numbers": self.password_require_numbers,
            "require_special": self.password_require_special
        }
    
    @property
    def audit_config(self) -> dict:
        """获取审计配置"""
        return {
            "enabled": self.enable_audit_log,
            "retention_days": self.audit_retention_days
        }
    
    @property
    def databases(self) -> Dict[str, Dict[str, Any]]:
        """
        生成命名数据库配置字典
        
        Returns:
            命名数据库配置，用于新的DatabaseManager
        """
        primary_config = {
            "url": self.user_primary_url,
            "pool_size": self.user_primary_pool_size,
            "pool_timeout": self.database_pool_timeout,
            "echo": self.database_echo,
            "role": "write",
            "type": "mysql"
        }
        
        databases_config = {
            "user_primary": primary_config,
            # 添加"primary"别名以保证向后兼容
            "primary": primary_config
        }
        
        # 如果配置了只读副本，添加到配置中
        if self.user_readonly_url:
            databases_config["user_readonly"] = {
                "url": self.user_readonly_url,
                "pool_size": self.user_readonly_pool_size,
                "pool_timeout": self.database_pool_timeout,
                "echo": self.database_echo,
                "role": "read",
                "type": "mysql"
            }
        
        # 如果配置了会话缓存，添加到配置中
        if self.session_cache_url:
            databases_config["session_cache"] = {
                "url": self.session_cache_url,
                "pool_size": self.session_cache_pool_size,
                "pool_timeout": self.database_pool_timeout,
                "echo": False,  # Redis通常不需要echo
                "role": "cache",
                "type": "redis"
            }
        
        return databases_config
    
    class Config:
        env_prefix = "USER_SERVICE_"
        case_sensitive = False
        env_file = Path(__file__).parent.parent / ".env"
        env_file_encoding = "utf-8"
